Skip to content

perf(sdk): make EventLog.append cost flat against conversation length - #4697

Merged
VascoSch92 merged 4 commits into
mainfrom
vasco/perf-4676-flat-eventlog-append
Sep 4, 2026
Merged

VascoSch92 merged 4 commits into
mainfrom
vasco/perf-4676-flat-eventlog-append

Conversation

@VascoSch92

@VascoSch92 VascoSch92 commented Aug 28, 2026 •

Copy link
Copy Markdown
Member

HUMAN:

Small perf to make append in log events constant.


AGENT:

Why

EventLog.append re-counted the whole events directory on every append to notice a
second writer, and it did so while holding the lock intake also waits on.
_count_events_on_disk lists the directory and, on LocalFileStore, stats every entry,
so appending event N costs O(N). Long conversations get progressively slower to write,
and the cost hides inside persistence rather than in anything that looks like "the agent".

Who the second writer actually is (the issue asks for this first): in this repository
there is exactly one writer per events directory. ConversationState owns the only
EventLog that appends to a conversation's events/; rerun_actions writes to a
separate directory it creates itself, and the tom_consult executor only reads other
conversations' logs. The guard still covers a second EventLog opened on the same
directory in the same process, which test_event_log_concurrent_writes_serialized
does deliberately. So this PR keeps the guard and makes it cheap rather than dropping it.

How the marker keeps this O(1)

BEFORE — every append:
  append() → list(events/) → stat EVERY file in the directory
                                   |
                    cost grows with log length (O(N) per append)
                    50k-event log ≈ 1.25 BILLION file stats total

AFTER — every append:
  append() → exists(".eventlog-len-N.marker")?
                   |
         ┌────yes──┴──no  (rare: a second writer appended)
         |                        |
    write event               count_events_on_disk()  [O(N), rare fallback]
    delete marker-N                |
    write marker-(N+1)        sync + continue
         |
    O(1) per append

Why delete the old marker instead of leaving it behind? Leftover markers would
accumulate in events/ forever, and the next fresh load/fork/resume
(_scan_and_build_index) lists that same directory — so it'd be 2x bigger,
and the O(N) cost this PR removes just moves to a different call site instead
of disappearing. The delete+write pair is 2 tiny file ops per append (100k
total on a 50k-event log), and that flat cost is exactly the "After" number
in the benchmark table below — not overhead on top of it.

Summary

  • EventLog.append now answers "has anyone appended since we last did?" with a single
    exists() probe of a sidecar marker whose name carries the event count. The exact
    count is still paid whenever the marker cannot prove the log is in sync, so multi-writer
    behavior is unchanged, never weaker.
  • A fixed-name counter file would not have worked: FileStore.read is cached, so a second
    process would keep serving its own stale value. FileStore.exists always hits the backend.
  • The old marker is deleted before the new one is written, so a writer killed between the
    two calls leaves no marker at all and every writer falls back to the exact count.
  • LocalFileStore.delete no longer raises on a cache miss. A file written by another process
    was never cached locally, and the swallowed KeyError logged a spurious ERROR on every
    cross-process marker handoff. Pre-existing, but this change is the first to hit it routinely.
  • Adds scripts/event_sourcing_benchmarks/bench_append_scaling.py, which measures append
    latency against log length. It synthesizes its own events, so it needs no --eval-dir.
  • Collects the dynamic ClientAction_* classes test_client_tools_persistence leaves
    behind. See the note at the bottom: the leak predates this branch, but removing the
    directory listing is what stops hiding it.

Issue Number

Fixes #4676

How to Test

1. The acceptance criterion: append cost is flat against log length

cd scripts/event_sourcing_benchmarks
python bench_append_scaling.py --events 4000

Median EventLog.append() latency per 400-event bucket, same machine, 4000 events:

Log length at append Before After
0 – 400 2.217ms 0.979ms
400 – 800 5.124ms 0.990ms
800 – 1,200 7.866ms 0.983ms
1,200 – 1,600 10.958ms 0.992ms
1,600 – 2,000 13.606ms 0.974ms
2,000 – 2,400 17.152ms 0.995ms
2,400 – 2,800 19.665ms 0.980ms
2,800 – 3,200 22.941ms 0.982ms
3,200 – 3,600 25.964ms 0.987ms
3,600 – 4,000 31.546ms 0.974ms
Growth factor 14.23x 1.00x

At 4000 events an append goes from 31.5ms to 1.0ms. Short logs get faster too, because
even a 400-event directory was being listed and stat'd on every append.

2. Two OS processes appending to one event directory

Unit tests share a FileStore (and its cache) inside one process, so they cannot exercise
the case the sync guard exists for. This script gives each process its own LocalFileStore,
then cold-loads the result in a third:

e2e_multiwriter.py
import multiprocessing as mp
import re, shutil, sys, tempfile

from openhands.sdk.conversation.event_store import EventLog
from openhands.sdk.event.llm_convertible import MessageEvent
from openhands.sdk.io import LocalFileStore
from openhands.sdk.llm import Message, TextContent

N_PER_PROC = 100

def make_event(tag, i):
    return MessageEvent(
        id=f"{tag:04x}{i:04x}-0000-0000-0000-000000000000",
        llm_message=Message(role="user", content=[TextContent(text=f"p{tag} e{i}")]),
        source="user",
    )

def writer(root, tag, errors):
    log = EventLog(LocalFileStore(root))
    for i in range(N_PER_PROC):
        try:
            log.append(make_event(tag, i))
        except Exception as e:
            errors.append(f"p{tag} e{i}: {type(e).__name__}: {e}")

def main():
    ctx = mp.get_context("spawn")
    root = tempfile.mkdtemp(prefix="e2e_multiwriter_")
    try:
        with ctx.Manager() as manager:
            errors = manager.list()
            procs = [ctx.Process(target=writer, args=(root, tag, errors)) for tag in range(2)]
            for p in procs: p.start()
            for p in procs: p.join()
            errors = list(errors)

        expected = 2 * N_PER_PROC
        fs = LocalFileStore(root)
        names = [n.rsplit("/", 1)[-1] for n in fs.list("events")]
        event_names = [n for n in names if n.startswith("event-")]
        markers = [n for n in names if ".marker" in n]
        indices = sorted(int(re.match(r"event-(\d+)-", n).group(1)) for n in event_names)
        log = EventLog(fs)  # fresh cold load from disk
        ids = [e.id for e in log]

        print(f"append errors:          {len(errors)}")
        print(f"event files on disk:    {len(event_names)} (expected {expected})")
        print(f"index range contiguous: {indices == list(range(expected))}")
        print(f"cold-loaded events:     {len(log)}")
        print(f"distinct event ids:     {len(set(ids))}")
        print(f"count markers left:     {len(markers)} {markers}")
        ok = (not errors and len(event_names) == expected
              and indices == list(range(expected)) and len(log) == expected
              and len(set(ids)) == expected and len(markers) == 1)
        print("\nRESULT:", "PASS" if ok else "FAIL")
        return 0 if ok else 1
    finally:
        shutil.rmtree(root, ignore_errors=True)

if __name__ == "__main__":
    sys.exit(main())
append errors:          0
event files on disk:    200 (expected 200)
index range contiguous: True
cold-loaded events:     200
distinct event ids:     200
count markers left:     1 ['.eventlog-len-200.marker']

RESULT: PASS

No lost or duplicated indices, no interleaving damage, and exactly one marker survives.
Run against the pre-fix code it also passes, so this is a parity check, not a new guarantee.

3. Tests

uv run pytest tests/sdk/ -q                   # 5973 passed, 0 failed
uv run pytest tests/agent_server/ -q          # 2083 passed, 0 failed
uv run pre-commit run --files <changed files> # all hooks pass

Four new tests in tests/sdk/conversation/test_event_store.py cover the flat-cost
guarantee (append must not list the directory as the log grows), a second writer still
being picked up, a legacy log that has no marker, and the scan no longer warning about
sidecar files. One new test in tests/sdk/io/test_filestore_cache.py covers the
delete() cache miss.

Type

  • Bug fix
  • Feature
  • Refactor
  • Breaking change
  • Docs / chore

Notes

  • On-disk change. The events directory gains one more dotfile sidecar next to the
    existing .eventlog.lock. Nothing in the repo enumerates that directory except
    EventLog itself, which already filters to event-*.json when counting. The cold scan
    now skips dotfiles silently instead of logging Unrecognized event file name for them,
    which also silences the warning .eventlog.lock has always produced. One existing test
    that counted files in the directory was updated to filter dotfiles rather than only .lock.
  • A latent class-registry leak this PR had to fix. test_client_tools_persistence
    registers the same client tool name twice (create, then resume), and each spec builds a
    new ClientAction_* class. Both are reachable only through reference cycles, so they stay
    in Action.__subclasses__() until a cyclic collection runs, and the duplicate-name check
    in _get_checked_concrete_subclasses then fails in unrelated later tests — three fork
    and state-serialization tests, with Duplicate class definition ... ClientAction_persist_navigate_to.
    The leak is pre-existing: on a clean main, running
    tests/sdk/conversation/local/test_client_tools_persistence.py together with
    tests/sdk/conversation/local/test_fork.py already fails. Full runs on main happened to
    pass because the old O(N) directory listing allocated enough garbage to trigger a
    collection in time; appending without it does not, which is how this PR surfaced it.
    Confirmed both directions: this branch with gc.set_threshold(100, 5, 5) is green without
    the fixture, and main with the fixture fixes the two-file failure. The fix is a teardown
    gc.collect() plus clear_subclass_cache() in that test module, so the leak stays local
    regardless of allocation patterns.
  • Not fixed here. tests/sdk/ and tests/agent_server/ run in a single pytest process
    produce 17 failures (ValueError: Local classes not supported! test_execute_tool.ContextAwareTool).
    This reproduces identically on a clean main from just
    tests/sdk/conversation/local/test_execute_tool.py plus
    tests/agent_server/test_openapi_discriminator.py, and is unrelated to this change.
    Both suites pass when run separately, as CI runs them.
  • Step 1 of [Epic] Streaming: separate the wire format from the durable event record #4671. The benchmark script is reusable for the other steps in that epic.

🐳 Agent Server images for this PR — GHCR package, pull/run commands, and all pushed tags (click to expand)

• GHCR package: https://github.com/OpenHands/agent-sdk/pkgs/container/agent-server

Variants & Base Images

Variant Architectures Base Image Docs / Tags
java amd64, arm64 eclipse-temurin:17-jdk Link
python-slim amd64, arm64 nikolaik/python-nodejs:python3.13-nodejs22-slim Link
python amd64, arm64 nikolaik/python-nodejs:python3.13-nodejs22-slim Link
golang amd64, arm64 golang:1.21-bookworm Link

Pull (multi-arch manifest)

# Each variant is a multi-arch manifest supporting both amd64 and arm64
docker pull ghcr.io/openhands/agent-server:99975b6-python

Run

docker run -it --rm \
  -p 8000:8000 \
  --name agent-server-99975b6-python \
  ghcr.io/openhands/agent-server:99975b6-python

All tags pushed for this build

ghcr.io/openhands/agent-server:99975b6-golang-amd64
ghcr.io/openhands/agent-server:99975b6edc6cd04993557cf6ce9144dab053387e-golang-amd64
ghcr.io/openhands/agent-server:vasco-perf-4676-flat-eventlog-append-golang-amd64
ghcr.io/openhands/agent-server:99975b6-golang_tag_1.21-bookworm-amd64
ghcr.io/openhands/agent-server:99975b6-golang-arm64
ghcr.io/openhands/agent-server:99975b6edc6cd04993557cf6ce9144dab053387e-golang-arm64
ghcr.io/openhands/agent-server:vasco-perf-4676-flat-eventlog-append-golang-arm64
ghcr.io/openhands/agent-server:99975b6-golang_tag_1.21-bookworm-arm64
ghcr.io/openhands/agent-server:99975b6-java-amd64
ghcr.io/openhands/agent-server:99975b6edc6cd04993557cf6ce9144dab053387e-java-amd64
ghcr.io/openhands/agent-server:vasco-perf-4676-flat-eventlog-append-java-amd64
ghcr.io/openhands/agent-server:99975b6-eclipse-temurin_tag_17-jdk-amd64
ghcr.io/openhands/agent-server:99975b6-java-arm64
ghcr.io/openhands/agent-server:99975b6edc6cd04993557cf6ce9144dab053387e-java-arm64
ghcr.io/openhands/agent-server:vasco-perf-4676-flat-eventlog-append-java-arm64
ghcr.io/openhands/agent-server:99975b6-eclipse-temurin_tag_17-jdk-arm64
ghcr.io/openhands/agent-server:99975b6-python-amd64
ghcr.io/openhands/agent-server:99975b6edc6cd04993557cf6ce9144dab053387e-python-amd64
ghcr.io/openhands/agent-server:vasco-perf-4676-flat-eventlog-append-python-amd64
ghcr.io/openhands/agent-server:99975b6-nikolaik_s_python-nodejs_tag_python3.13-nodejs22-slim-amd64
ghcr.io/openhands/agent-server:99975b6-python-arm64
ghcr.io/openhands/agent-server:99975b6edc6cd04993557cf6ce9144dab053387e-python-arm64
ghcr.io/openhands/agent-server:vasco-perf-4676-flat-eventlog-append-python-arm64
ghcr.io/openhands/agent-server:99975b6-nikolaik_s_python-nodejs_tag_python3.13-nodejs22-slim-arm64
ghcr.io/openhands/agent-server:99975b6-python-slim-amd64
ghcr.io/openhands/agent-server:99975b6edc6cd04993557cf6ce9144dab053387e-python-slim-amd64
ghcr.io/openhands/agent-server:vasco-perf-4676-flat-eventlog-append-python-slim-amd64
ghcr.io/openhands/agent-server:99975b6-nikolaik_s_python-nodejs_tag_python3.13-nodejs22-slim-slim-amd64
ghcr.io/openhands/agent-server:99975b6-python-slim-arm64
ghcr.io/openhands/agent-server:99975b6edc6cd04993557cf6ce9144dab053387e-python-slim-arm64
ghcr.io/openhands/agent-server:vasco-perf-4676-flat-eventlog-append-python-slim-arm64
ghcr.io/openhands/agent-server:99975b6-nikolaik_s_python-nodejs_tag_python3.13-nodejs22-slim-slim-arm64
ghcr.io/openhands/agent-server:99975b6-golang
ghcr.io/openhands/agent-server:99975b6edc6cd04993557cf6ce9144dab053387e-golang
ghcr.io/openhands/agent-server:vasco-perf-4676-flat-eventlog-append-golang
ghcr.io/openhands/agent-server:99975b6-golang_tag_1.21-bookworm
ghcr.io/openhands/agent-server:99975b6-java
ghcr.io/openhands/agent-server:99975b6edc6cd04993557cf6ce9144dab053387e-java
ghcr.io/openhands/agent-server:vasco-perf-4676-flat-eventlog-append-java
ghcr.io/openhands/agent-server:99975b6-eclipse-temurin_tag_17-jdk
ghcr.io/openhands/agent-server:99975b6-python-slim
ghcr.io/openhands/agent-server:99975b6edc6cd04993557cf6ce9144dab053387e-python-slim
ghcr.io/openhands/agent-server:vasco-perf-4676-flat-eventlog-append-python-slim
ghcr.io/openhands/agent-server:99975b6-nikolaik_s_python-nodejs_tag_python3.13-nodejs22-slim-slim
ghcr.io/openhands/agent-server:99975b6-python
ghcr.io/openhands/agent-server:99975b6edc6cd04993557cf6ce9144dab053387e-python
ghcr.io/openhands/agent-server:vasco-perf-4676-flat-eventlog-append-python
ghcr.io/openhands/agent-server:99975b6-nikolaik_s_python-nodejs_tag_python3.13-nodejs22-slim

About Multi-Architecture Support

  • Each variant tag (e.g., 99975b6-python) is a multi-arch manifest supporting both amd64 and arm64
  • Docker automatically pulls the correct architecture for your platform
  • Individual architecture tags (e.g., 99975b6-python-amd64) are also available if needed

EventLog.append counted every file in the events directory on each append
to detect a second writer, so appending event N cost O(N) directory work
while holding the lock that intake also wants.

Replace the count with an O(1) probe of a sidecar marker whose name carries
the event count. The exact count is still paid whenever the marker cannot
prove the log is in sync, so multi-writer behavior is unchanged.

Also stop LocalFileStore.delete from raising on a cache miss: a file written
by another process was never cached locally, and deleting it logged a
spurious ERROR on every cross-process marker handoff.
@github-actions

github-actions Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Python API breakage checks — ✅ PASSED

Result: ✅ PASSED

Action log

@github-actions

github-actions Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

REST API breakage checks (OpenAPI) — ✅ PASSED

Result: ✅ PASSED

Action log

@github-actions

github-actions Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Coverage

Coverage Report •
FileStmtsMissCoverMissing
openhands-sdk/openhands/sdk/conversation
   event_store.py2152190%163, 166, 179, 183–184, 240, 244, 257–259, 270–271, 277, 279–282, 303, 305, 353, 367
openhands-sdk/openhands/sdk/io
   local.py88891%70–71, 97, 122–123, 131, 143–144
TOTAL410781142572% 

…leak

- Shorten the marker comments and docstrings; type LENGTH_MARKER_PATTERN
  as Final[str].
- Collect the dynamic ClientAction_* classes that
  test_client_tools_persistence leaves behind. Registering the same client
  tool name twice creates two same-named classes that are reachable only
  through reference cycles, so they sit in Action.__subclasses__() until a
  cyclic collection runs and make the duplicate-class check fail in
  unrelated later tests.

  The leak predates this branch: test_client_tools_persistence.py plus
  test_fork.py already fail together on main. It stayed hidden in full runs
  because the old O(N) directory listing allocated enough garbage to trigger
  collection in time; appending without it does not.
@VascoSch92
VascoSch92 marked this pull request as ready for review August 28, 2026 10:45
@all-hands-bot

all-hands-bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Collaborator

🚦 CI is currently failing on this PR's latest commit.

Please fix the failing checks before OpenHands reviews it - this is re-checked automatically once you push a new commit. (A maintainer can also request @all-hands-bot as a reviewer to have it reviewed regardless of CI status.)

This is an automated check - no AI was used to generate this comment.

@all-hands-bot

Copy link
Copy Markdown
Collaborator

🚦 CI is currently failing on this PR's latest commit.

Please fix the failing checks before OpenHands reviews it - this is re-checked automatically once you push a new commit. (A maintainer can also request @all-hands-bot as a reviewer to have it reviewed regardless of CI status.)

This is an automated check - no AI was used to generate this comment.

1 similar comment
@all-hands-bot

Copy link
Copy Markdown
Collaborator

🚦 CI is currently failing on this PR's latest commit.

Please fix the failing checks before OpenHands reviews it - this is re-checked automatically once you push a new commit. (A maintainer can also request @all-hands-bot as a reviewer to have it reviewed regardless of CI status.)

This is an automated check - no AI was used to generate this comment.

@all-hands-bot

Copy link
Copy Markdown
Collaborator

🚦 CI is currently failing on this PR's latest commit.

Please fix the failing checks before OpenHands reviews it - this is re-checked automatically once you push a new commit. (A maintainer can also request @all-hands-bot as a reviewer to have it reviewed regardless of CI status.)

This is an automated check - no AI was used to generate this comment.

@github-actions

github-actions Bot commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

Endpoint audit

⚠️ 18 actionable Agent Server contract divergence(s) · report-only

Contract: pinned release artifact

Category Count
Actionable client-only calls 0
Actionable server-only operations 18
Documented non-divergences 13
Agent Server contract operations 129
Audited handwritten client endpoints 119

Actionable client-only calls (0)

none

Actionable server-only operations (18)

  • DELETE /api/canvas-extensions/installed/{}
  • DELETE /api/llm/provider-connections/{}
  • GET /api/canvas-extensions/installed
  • GET /api/canvas-extensions/installed/{}
  • GET /api/canvas-extensions/installed/{}/bundle
  • GET /api/conversations/{}/events
  • GET /api/file/archive
  • GET /api/git/commits
  • GET /api/git/commits/{}/changes
  • GET /api/init
  • GET /api/llm/provider-connections
  • PATCH /api/canvas-extensions/installed/{}
  • PATCH /api/llm/provider-connections/{}
  • POST /api/canvas-extensions/install
  • POST /api/conversations/{}/load_plugin
  • POST /api/file/create_directory
  • POST /api/init
  • POST /api/llm/provider-connections
Documented non-divergences (13)

Client calls intentionally absent from the filtered contract (11)

  • GET /
  • GET /alive
  • GET /health
  • GET /ready
  • GET /server_info

Reason: Operational Agent Server endpoints intentionally excluded from the filtered public release artifact.
Owner: OpenHands runtime maintainers

  • DELETE /api/meta-profiles/{}
  • GET /api/meta-profiles
  • GET /api/meta-profiles/{}
  • POST /api/meta-profiles/{}
  • POST /api/meta-profiles/{}/activate

Reason: Client-ahead API stacked on the pending Agent Server meta-profiles implementation.
Owner: OpenHands SDK maintainers
Tracking: #3744

  • POST /api/profiles/{}/validate

Reason: Client-ahead API stacked on the pending Agent Server pre-flight LLM validation endpoint.
Owner: OpenHands TypeScript client maintainers
Tracking: #4422

Server operations covered by an exposed browser URL (2)

  • GET /api/conversations/{}/workspace
  • GET /api/conversations/{}/workspace/{}

Reason: RemoteWorkspace.startWorkspaceSession exposes these authenticated URLs for browser iframe and file requests; they are not HttpClient method calls.
Owner: OpenHands TypeScript client maintainers

@VascoSch92

Copy link
Copy Markdown
Member Author

@all-hands-bot fix the conflicts in this PR

Co-authored-by: openhands <openhands@all-hands.dev>
@all-hands-bot

Copy link
Copy Markdown
Collaborator

Resolved the conflicts by merging the latest main into the PR branch and preserving both the EventLog marker update and append()'s newly returned index.

Pushed merge commit 99975b6e. GitHub now reports the PR as mergeable with no conflicts.

Validation:

  • uv run pytest tests/sdk/conversation/test_event_store.py tests/sdk/io/test_filestore_cache.py tests/sdk/conversation/local/test_client_tools_persistence.py -q — 50 passed
  • uv run pre-commit run --files openhands-sdk/openhands/sdk/conversation/event_store.py tests/sdk/conversation/test_event_store.py — passed

Generated by OpenHands AI on behalf of the user.

@all-hands-bot

Copy link
Copy Markdown
Collaborator

🤖 OpenHands is reviewing this PR.

Head commit: 99975b6edc6cd04993557cf6ce9144dab053387e
View the conversation: https://oss-agent-canvas.ngrok.dev/conversations/810ad7f8-99ab-480f-9f60-3744cb443fde

This comment was posted by an AI agent (OpenHands).

@all-hands-bot

Copy link
Copy Markdown
Collaborator

⚠️ OpenHands PR Reviewer encountered a problem at commit 99975b6edc6c (status: error).

This comment was posted by an AI agent (OpenHands).

@VascoSch92
VascoSch92 merged commit b22877c into main Sep 4, 2026
52 checks passed
@VascoSch92
VascoSch92 deleted the vasco/perf-4676-flat-eventlog-append branch September 4, 2026 16:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Perf] EventLog.append lists the entire event directory on every append

4 participants